//
//  UITextView+Emoticon.swift
//  01-表情键盘 Emotion
//
//  Created by wulei on 15/12/16.
//  Copyright © 2015年 wulei. All rights reserved.
//

import UIKit

extension UITextView {

    var emoticonText: String {
        var strM = String()
        let attrText = attributedText
        
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: []) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment{
                strM += attachment.emoticon.chs ?? ""
            }else {
                let str = (attrText.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        
        return strM
    }

    func InsertEmoticon(em:Emoticon){

        
        // 空表情
        if em.isEmpty {
            return
        }
        
        // 删除
        if em.isRemoved {
            deleteBackward()
            return
        }
        
        // 插入表情符号
        if let emoji = em.emoji {
            
            // selectedTextRange -> UITextRange
            replaceRange(selectedTextRange!, withText: emoji)
            return
        }
        
        // 插入图片
        insertImageEmoticon(em)
        
        if hasText() {
            print("has Text")
        }else{
            print("no has Text")
        }
        
        
        
        // 5. 通知`代理`文本变化了 － textViewDidChange? 表示代理如果没有实现方法，就什么都不做，更安全
        delegate?.textViewDidChange?(self)

        
    }
    
    func insertImageEmoticon(em:Emoticon) {
        
       let imageText = EmoticonAttachment(emoticon: em).imageText(font!)
        
        // 记录 textView 将textView 里的文本attributedString 转换成可变文本
        let strM = NSMutableAttributedString(attributedString: attributedText)
        
        
        
        // 插入图片文本                       ->  NSRange
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        
        
        // **********注意代码执行顺序*********
        // 记录光标位置
        let range = selectedRange
        // 整体替换文本
        attributedText = strM
        // 恢复光标的位置
        selectedRange = NSRange(location: range.location + 1, length: 0)
        
        
        
        
        
    }

}
